package com.central.apps.handler.timeTask.project;

import com.central.app.common.quartz.QuartzJob;
import com.central.app.service.HandlerService;
import com.central.apps.entity.BlMessage;
import com.central.apps.service.MessageService;
import com.central.bizcommon.model.schedule.JobParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
//禁止并发执行(Quartz不要并发地执行同一个job定义（这里指一个job类的多个实例）)
@DisallowConcurrentExecution
public class TaskWarnTask extends QuartzJob {
    @Autowired
    private HandlerService handlerService;
    @Autowired
    private MessageService messageService;

    /**
     * 任务
     *
     * @param context
     * @param jobnum
     * @param jobname
     * @param jobparams
     */
    @Override
    public void executeJob(JobExecutionContext context, String jobnum, String jobname, List<JobParams> jobparams) {
        if (CollectionUtils.isEmpty(jobparams)) {
            List<Map<String, Object>> list = handlerService.findBySql("SELECT * FROM task_schedule_job_params WHERE (jobid in (select jobId from task_schedule_job where jobnum = '" + jobnum + "'))");

            if (CollectionUtils.isNotEmpty(list)) {
                for (Map<String, Object> map : list) {
                    JobParams jobParams = new JobParams();
                    jobParams.setParamkey(MapUtils.getString(map, "paramkey"));
                    jobParams.setParamvalue(MapUtils.getString(map, "paramvalue"));

                    jobparams.add(jobParams);
                }
            }
        }

        if (CollectionUtils.isNotEmpty(jobparams)) {
            for (JobParams jobParams : jobparams) {
                // 查询项目预警配置信息
                List<Map<String, Object>> cfgList = handlerService.findBySql("select * from gq_protaskwarn t where t.tablename = 'gq_mytask' and t.nodedesc = '" + jobParams.getParamvalue() + "'");

                if (CollectionUtils.isEmpty(cfgList)) {
                    return;
                }

                Map<String, Object> cfgMap = cfgList.get(0);
                Integer pwid = MapUtils.getInteger(cfgMap, "id");
                String calculateFormat = MapUtils.getString(cfgMap, "calculateformat");
                String tableName = MapUtils.getString(cfgMap, "tablename");
                String fieldName = MapUtils.getString(cfgMap, "fieldname");
                String nodeDesc = MapUtils.getString(cfgMap, "nodedesc");

                List<Map<String, Object>> cfgDtlList = handlerService.findBySql("select * from gq_protaskwarndtl t where t.ptwid = " + pwid);

                if (CollectionUtils.isEmpty(cfgDtlList)) {
                    return;
                }

                // 获取当前日期
                Date date = new Date();
                String dateStr = "";
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                dateStr = dateFormat.format(date);

                for (Map<String, Object> cfgDtlMap : cfgDtlList) {
                    StringBuilder sql = new StringBuilder();
                    sql.append("select * from ");
                    sql.append(tableName);
                    sql.append(" where iswarnflag = '1' and ");

                    String timeunitDesc = MapUtils.getString(cfgDtlMap, "timeunitdesc");
                    String calculatefrom = MapUtils.getString(cfgDtlMap, "calculatefrom");
                    String calculateto = MapUtils.getString(cfgDtlMap, "calculateto");
                    Integer timeparamfrom = MapUtils.getInteger(cfgDtlMap, "timeparamfrom");
                    Integer timeparamto = MapUtils.getInteger(cfgDtlMap, "timeparamto");
                    String fieldname = MapUtils.getString(cfgDtlMap, "fieldname");
                    String schedulestatus = MapUtils.getString(cfgDtlMap, "schedulestatus");
                    String msgformat = MapUtils.getString(cfgDtlMap, "msgformat");

                    // 时间单位分支处理
                    switch (timeunitDesc) {
                        case "天":
                            switch (calculateFormat) {
                                case "提前":
                                    // 获取运算符号
                                    String calculateSign = getCalculateSign(calculatefrom);
                                    sql.append("date_add(");
                                    sql.append(fieldName);
                                    sql.append(" ,interval -");
                                    sql.append(timeparamfrom);
                                    sql.append(" day) ");
                                    sql.append(calculateSign);
                                    sql.append(" str_to_date('");
                                    sql.append(dateStr);
                                    sql.append("', '%Y-%m-%d')");
                                    break;
                                case "滞后":
                                    // 获取运算符号
                                    String calculateSignFrom = getCalculateSign(calculatefrom);

                                    sql.append(" str_to_date('");
                                    sql.append(dateStr);
                                    sql.append("', '%Y-%m-%d')");
                                    sql.append(calculateSignFrom);
                                    sql.append(" date_add(");
                                    sql.append(fieldName);
                                    sql.append(" ,interval ");
                                    sql.append(timeparamfrom);
                                    sql.append(" day) ");

                                    if (StringUtils.isNotEmpty(calculateto)) {
                                        // 获取运算符号
                                        String calculateSignTo = getCalculateSign(calculateto);
                                        sql.append(" and str_to_date('");
                                        sql.append(dateStr);
                                        sql.append("', '%Y-%m-%d')");
                                        sql.append(calculateSignTo);
                                        sql.append(" date_add(");
                                        sql.append(fieldName);
                                        sql.append(" ,interval ");
                                        sql.append(timeparamto);
                                        sql.append(" day) ");
                                    }

                                    break;
                                default:
                                    break;
                            }
                            break;
                        case "小时":
                            switch (calculateFormat) {
                                case "提前":
                                    // 获取运算符号
                                    String calculateSign = getCalculateSign(calculatefrom);
                                    sql.append("date_add(");
                                    sql.append(fieldName);
                                    sql.append(" ,interval -");
                                    sql.append(timeparamfrom);
                                    sql.append(" hour) ");
                                    sql.append(calculateSign);
                                    sql.append(" str_to_date('");
                                    sql.append(dateStr);
                                    sql.append("', '%Y-%m-%d %H:%i:%S')");
                                    break;
                                case "滞后":
                                    // 获取运算符号
                                    String calculateSignFrom = getCalculateSign(calculatefrom);
                                    sql.append(" str_to_date('");
                                    sql.append(dateStr);
                                    sql.append("', '%Y-%m-%d %H:%i:%S')");
                                    sql.append(calculateSignFrom);
                                    sql.append(" date_add(");
                                    sql.append(fieldName);
                                    sql.append(" ,interval ");
                                    sql.append(timeparamfrom);
                                    sql.append(" hour) ");

                                    if (StringUtils.isNotEmpty(calculateto)) {
                                        // 获取运算符号
                                        String calculateSignTo = getCalculateSign(calculateto);

                                        sql.append(" and str_to_date('");
                                        sql.append(dateStr);
                                        sql.append("', '%Y-%m-%d %H:%i:%S')");
                                        sql.append(calculateSignTo);
                                        sql.append(" date_add(");
                                        sql.append(fieldName);
                                        sql.append(" ,interval ");
                                        sql.append(timeparamto);
                                        sql.append(" hour) ");

                                    }

                                    break;
                                default:
                                    break;
                            }
                            break;
                        default:
                            break;
                    }

                    List<Map<String, Object>> list = handlerService.findBySql(sql.toString());

                    if (CollectionUtils.isNotEmpty(list)) {
                        // 组织消息内容
                        for (Map.Entry<String, Object> entry : cfgDtlMap.entrySet()) {
                            if (msgformat.contains("{" + entry.getKey() + "}")) {
                                msgformat = msgformat.replace("{" + entry.getKey() + "}", entry.getValue().toString());
                            }
                        }

                        for (Map<String, Object> map : list) {
                            Integer id = MapUtils.getInteger(map, "id");// id
                            Integer manager = MapUtils.getInteger(map, "manager");// 任务负责人
                            String managerName = MapUtils.getString(map, "managername");// 任务负责人名称
                            String assigns = MapUtils.getString(map, "assigns");// 分派人员
                            String assignsdesc = MapUtils.getString(map, "assignsdesc");// 分派人员名称

                            // 更新数据
                            if (StringUtils.isNotEmpty(fieldname) && StringUtils.isNotEmpty(schedulestatus)) {
                                handlerService.updateBySql("update " + tableName + " set " + fieldname + " = '" + schedulestatus + "' where id = " + id);

                                // 更新计划状态
                                Integer taskId = MapUtils.getInteger(map, "taskid");// id
                                if (taskId > 0) {
                                    handlerService.updateBySql("update gq_scheduleplantask set " + fieldname + " = '" + schedulestatus + "' where id = " + taskId);
                                }
                            }

                            // 通知任务负责人
                            BlMessage message = new BlMessage();
                            message.setTitle(nodeDesc);
                            message.setContent(msgformat);
                            message.setIsshow("未读");
                            message.setRecipient(manager.toString());
                            message.setRecipientname(managerName);

                            message.setCreateuser("0");
                            message.setCreateuserdesc("系统");
                            messageService.addMessage(message);

                            if (StringUtils.isNotEmpty(assigns)) {
                                String[] assignsArray = assigns.split(",");
                                String[] assignsDescArray = assignsdesc.split(",");
                                for (int i = 0; i < assignsArray.length; i++) {
                                    // 通知任务分派人员
                                    message.setRecipient(assignsArray[i]);
                                    message.setRecipientname(assignsDescArray[i]);
                                    messageService.addMessage(message);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 获得运算符号
     *
     * @param calculateWay
     * @return
     */
    private String getCalculateSign(String calculateWay) {
        String calculateSign = "=";
        switch (calculateWay) {
            case "大于":
                calculateSign = ">";
                break;
            case "小于":
                calculateSign = "<";
                break;
            case "大于等于":
                calculateSign = ">=";
                break;
            case "小于等于":
                calculateSign = "<=";
                break;
            default:
                break;
        }

        return calculateSign;
    }
}
